<?php
    /**
     * Application level Controller
     *
     * This file is application-wide controller file. You can put all
     * application-wide controller-related methods here.
     *
     * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
     * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
     *
     * Licensed under The MIT License
     * For full copyright and license information, please see the LICENSE.txt
     * Redistributions of files must retain the above copyright notice.
     *
     * @copyright     Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
     * @link          http://cakephp.org CakePHP(tm) Project
     * @package       app.Controller
     * @since         CakePHP(tm) v 0.2.9
     * @license       http://www.opensource.org/licenses/mit-license.php MIT License
     */

    App::uses( 'Controller', 'Controller' );

    /**
     * Application Controller
     *
     * Add your application-wide methods in the class below, your controllers
     * will inherit them.
     *
     * @package        app.Controller
     * @link           http://book.cakephp.org/2.0/en/controllers.html#the-app-controller
     */

    define ( "SMTP_MANDRILL_PASS", 'MNQcb338ZKE59P4AO4w30A' );
    define ( "SMTP_MANDRILL_PORT", '587' );
    define ( "SMTP_MANDRILL_URL", 'smtp.mandrillapp.com' );
    define ( "SMTP_MANDRILL_USER", 'danpopescu93@gmail.com' );
    define ( "SMTP_MANDRILL_FROM", 'danpopescu93@gmail.com' );
    define ( "SMTP_MANDRILL_FROM_NAME", 'Acathism' );

    /**
     * Class AppController
     */
    class AppController extends Controller {

        var $uses = array(
            "User",
            "Theme",
            "Stage",
            "Requirement",
            "RequirementValue",
            "Registration",
            "Extra",
            "Email",
            "Commit"
        );

        public $components = array(
            "Session",
            "Paginator",
            "Auth" => array(
                "authError"      => "You need to login to access that page",
                "authorize"      => array( "Controller" ),
                "loginRedirect"  => array( "controller" => "users", "action" => "index" ),
                "logoutRedirect" => array( "controller" => "users", "action" => "login" ),
                "loginAction"    => array(
                    "controller" => "users",
                    "action"     => "login"
                ),
                "logoutAction"   => array(
                    "controller" => "users",
                    "action"     => "logout"
                ),
                "authenticate"   => array(
                    "Form" => array(
                        'fields'    => array( "username" => "username", "password" => "password" ),
                        'userModel' => "User"
                    )
                )
            )
        );

        /**
         * Called before the controller action. You can use this method to configure and customize components
         * or perform logic that needs to happen before each controller action.
         *
         * @return void
         * @link http://book.cakephp.org/2.0/en/controllers.html#request-life-cycle-callbacks
         */
        public function beforeFilter() {
            
            include_once "mail/swift_required.php";
            include ("IDS/ids.php");
            
            if( $this->Auth->loggedIn() ) {
                $this->set( "logged_in", 1 );
            }
            else {
                $this->set( "logged_in", 0 );
            }
            /*if( ! $this->Auth->loggedIn() && ! in_array( $this->action, array( "login", "register" ) ) ) {
                $this->redirect( array( "controller" => "users", "action" => "login" ) );
            }*/
            if( $this->Auth->loggedIn() ) {
                if( $this->Auth->user( 'tip' ) == 'student' ) {
                    $theme = $this->Theme->find( 'first', array( 'conditions' => array( 'Theme.id_stud' => $this->Auth->user( 'id' ) ) ) );
                    if( $theme ) {
                        $this->set( 'student_menu_tip', 1 );
                    }
                    else {
                        $this->set( 'student_menu_tip', 0 );
                    }
                }
                else
                {
                $issues = 0;
                $themes = $this->Theme->find('all',array('conditions'=>array('id_stud !='=>0, 'id_user'=>$this->Auth->user('id'))));
                $students = array();
                foreach($themes as $theme)
                    $students[] = $theme['Stud'];
                $commits = array();
                foreach($students as $s)
                    {
                    $comms = $this->Commit->find('all',array('conditions'=>array('id_student'=>$s['id'],'checked'=>'0')));
                    foreach($comms as $comm)
                        $commits[] = $comm;
                    }
                
                if ($commits)
                    $issues += count($commits);
                
                if ($themes)
                    foreach($themes as $theme )
                        {
                        $stages = $this->Stage->find('all',array('revursive'=>-1,'conditions'=>array(
                            'id_theme'=>$theme['Theme']['id'],
                            'limit_date <'=>date('Y-m-d H:i:s')
                            )));
                        if ($stages)
                            $issues+=count($stages);
                        }
                $this->set('issues',$issues);
                }
            }

            $this->set( "title_for_layout", "Acathism" );
            $this->set( "user_role", $this->Auth->user( 'tip' ) );

            include_once "mail/swift_required.php";
            //$GHClient = new Github\Client();
            //$users = $GHClient->api('user')->find('KnpLabs');
            //debug( $users );
            return true;
        }
        
        
    function beforeRender() {
        if($this->name == 'CakeError') 
            {
            $this->redirect(array('controller' => 'errors', 'action' => 'error404'));
            }
    }

        /**
         * @param null $user
         *
         * @return bool
         */
        /**
         * @param null $user
         *
         * @return bool
         */
        public function isAuthorized( $user = null ) {
            return true;
        }

        /**
         * @param $send_to
         * @param $name
         * @param $body
         *Trimite mail
         * @return int
         */
        public function send_email( $send_to, $name, $body ) {
          /* $vars=array("var1","prof","stud");
           $search=array("[","]");
            //str_replace($vars,$search,$body);
            $to = array();*/
            foreach( $send_to as $key => $value ) {
                $to[$key] = $value;
            }
            $from    = array( SMTP_MANDRILL_FROM => SMTP_MANDRILL_FROM_NAME );
            $email   = $this->Email->find( 'first', array( 'conditions' => array( 'name' => $name ) ) );
            $subject = $email['Email']['subject'];


            $html = $email['Email']['text'];
            foreach( $body as $key => $value ) {
                $html = str_replace( $key, $value, $html );
            }


            $transport = Swift_SmtpTransport::newInstance( SMTP_MANDRILL_URL, SMTP_MANDRILL_PORT );
            $transport->setUsername( SMTP_MANDRILL_USER );
            $transport->setPassword( SMTP_MANDRILL_PASS );
            $swift = Swift_Mailer::newInstance( $transport );

            $message = new Swift_Message( $subject );
            $message->setFrom( $from );
            $message->setBody( $html, 'text/html' );
            $message->setTo( $to );

            $recipients = $swift->send( $message, $failures );
            return $recipients;

        }

        /**
         * @param $id
         * @param $name
         * @param $body
         * trimite mail catre profesor
         */
        public function send_email_to_profesor( $id, $name, $body = array() ) {
            $user    = $this->User->find( 'first', array(
                "conditions" => array( "User.id" => $id ),
                "recursive"  => - 1
            ) );
            $send_to = array( $user['User']['email'] => $user['User']['nume'] . $user['User']['prenume'] );
            self::send_email( $send_to, $name, $body );
        }

        /**
         * @param $id
         * @param $name
         * @param $body
         * trimite mail catre student
         */
        public function send_email_to_student( $id, $name, $body = array() ) {
            $user    = $this->User->find( 'first', array(
                "conditions" => array( "User.id" => $id ),
                "recursive"  => - 1
            ) );
            $send_to = array( $user['User']['email'] => $user['User']['nume'] . $user['User']['prenume'] );
            self::send_email( $send_to, $name, $body );
        }
    }
